package com.motong.gongdan.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.motong.gongdan.config.interceptor.TenantLineInnerInterceptor;
import com.motong.gongdan.util.LoginUtil;
import net.sf.jsqlparser.expression.LongValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:fff
 * @time:2022/3/30
 */
@Configuration
@MapperScan(basePackages = {"com.motong.gongdan.mapper"})
public class MybatisPlusConfig {


    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public LongValue getTenantId() {
                return new LongValue(LoginUtil.getLoginUserFactory());
            }
            @Override
            public String getTenantIdColumn() {
                return "factory_id";
            }
            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                Map<String, Boolean> expectTable = new HashMap<>();
//                expectTable.put("user", true);
                expectTable.put("factory", true);
                expectTable.put("database_list", true);
                expectTable.put("user_menu",true);
                expectTable.put("t_calendar_auxiliary",true);
                expectTable.put("dict_event",true);
                expectTable.put("num",true);
                return expectTable.getOrDefault(tableName, false);
            }
        }));
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }



    /*
     * 分页插件，自动识别数据库类型
     * 多租户，请参考官网【插件扩展】
     */
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
//        // paginationInterceptor.setOverflow(false);
//        // 设置最大单页限制数量，默认 500 条，-1 不受限制
//        // paginationInterceptor.setLimit(500);
//        // 开启 count 的 join 优化,只针对部分 left join
//        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
//        return paginationInterceptor;
//    }
}
